<template>
    <h2 style="text-align: center;">用户投资页面</h2>
    <table>
       <tr>
           <td>项目名称</td>
           <td>
             {{info.I_Name}}
           </td>
       </tr>
       <tr>
           <td>总投资金额</td>
           <td> 
               {{info.I_Budget}}
           </td>
       </tr>
       <tr>
           <td>已投金额</td>
           <td>
               {{info.I_Receive}}
           </td>
       </tr>
       <tr>
           <td>剩余金额</td>
           <td>
              {{info.I_Residue}}
           </td>
       </tr>
       <tr>
           <td>投资金额</td>
           <td>
               <input type="text" v-model="Imoney" @change="GetMoneyApy"/>    
           </td>
       </tr>
       <tr>
        <td>预期最高收益</td>
        <td>
            {{Iapy.toFixed(2)}}CNY
        </td>
       </tr>
       <tr>
           <td colspan="2" style="text-align: center;">
              <input type="button" value="确认投资" @click="SaveData" />
           </td>
       </tr>
    </table>
</template>

<script setup lang="ts">
import { useRoute} from 'vue-router';
import {ref,onMounted} from 'vue';
import axios from 'axios';
import {useUserStore} from '../../Store/Index.ts'

//创建仓库实例
const UserStore = useUserStore();

const route = useRoute();

alert(route.params.Iid);




//创建响应式数据
const info = ref({
    I_Name:"",
    I_Budget:0,
    I_Receive:0,
    I_Residue:0,
})

//创建投资金额响应式数据
const Imoney = ref("");

//创建预期最高收益响应式数据
const Iapy = ref(0);

//生命周期函数勾
onMounted(()=>{
    LoadInfo();
})

const LoadInfo = ()=>{
      axios({
         url:"https://localhost:44337/api/Invests/Backfill",
         method:"get",
         params:{
             Iid:route.params.Iid
         }
      }).then(res=>{
          console.log(res.data);
          info.value.I_Name = res.data.I_Name;
          info.value.I_Budget = res.data.I_Budget;
          info.value.I_Receive = res.data.I_Receive;
          info.value.I_Residue = res.data.I_Residue;
          
      }).catch(err=>{
          console.log(err);
      })
}
//获取最高收益
const GetMoneyApy =() =>{
     Iapy.value =Number(Imoney.value)*1.3/100;
}

//添加用户投资信息
const SaveData = ()=>{
    if(Imoney.value=="")
    {
        alert("投资金额不能为空");
        return;
    }
    //判断用户投资金额需大于0且小于剩余投资金额
    if(Number(Imoney.value)<=0||Number(Imoney.value)>info.value.I_Residue)
    {
        alert("投资金额需大于0且小于剩余投资金额");
        return;
    }
    axios({
        url:"https://localhost:44337/api/Invests/AddUserInvestInfo",
        method:"post",
        data:{
            I_Id:route.params.Iid,
            U_Id:UserStore.Uid,
            UI_Money:Number(Imoney.value)
        }
    }).then(res=>{
        if(res.data>0)
        {
            alert("投资成功");
        } else
        {
            alert("投资失败");
        }
    })
}
</script>